package com.logic.view

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.logic.adapter.RfidAdapter
import com.logic.idevice.IUHFScan.*
import com.sinopec.basemodule.base.BasePresenter
import com.sinopec.basemodule.base.basekt.BaseActivityKt
import com.sinopec.basemodule.dialog.*
import com.sinopec.basemodule.utils.ToastUtils
import com.uhf.uhf.R
import com.uhf.uhf.kernel.uhfKernel
import kotlinx.android.synthetic.main.bm_a_uhf.*
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.LinkedHashSet

/**
 * RFID base界面
 */
abstract class BaseUhfActivity<P : BasePresenter>(title: String) : BaseActivityKt<P>(
    R.layout.bm_a_uhf,
    title
) {
    var rate = 0
    var time = 0L
    val uhfKernel = uhfKernel {
        speed = IRefreshSpeed { count, rate, time ->
            setHintTv(mItemList.size, rate, time)
        }
        data = IRefreshData { codes ->
            val empList = ArrayList<String>()
            empList.addAll(normalList)
            empList.addAll(codes)
            val codeSet = LinkedHashSet<String>(empList)
            val newList = ArrayList<String>(codeSet)

            codes.forEach {
                if (!newList.contains(it)) {
                    newList.add(it)
                }
            }

            refreshList(newList)
        }

        state = IScanStatus {
            if (it) {
                start_iv!!.setImageResource(R.drawable.ic_uhf_stop)
            } else {
                start_iv!!.setImageResource(R.drawable.ic_uhf_start)
            }
        }
    }

    private val mItemList = ArrayList<String>()

    // private var keyReceiver: KeyReceiver? = null

    //正常托盘
    var normalList = ArrayList<String>()

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        return uhfKernel.uhfKeyEventCall.onKeyDown(keyCode, event) || super.onKeyDown(
            keyCode,
            event
        )
    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
        return uhfKernel.uhfKeyEventCall.onKeyUp(keyCode, event) || super.onKeyUp(keyCode, event)
    }

    /**
     * 优博讯手持手柄按下事件
     *
     * @param event
     * @return
     */
    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        if (event.keyCode == 523 && event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
            //手持按键点击事件-按下
            uhfKernel.scan.startOrStop(true)
            return true
        } else if (event.keyCode == 523 && event.action == KeyEvent.ACTION_UP && event.repeatCount == 0) {
            //手持按键点击事件-抬起
            uhfKernel.scan.startOrStop(false)
            return true
        }
        return super.dispatchKeyEvent(event)
    }

    @SuppressLint("MissingPermission")
    override fun initView(savedInstanceState: Bundle?) {
        setHintTv(0, 0, 0)
        rv!!.also {
            it.layoutManager = LinearLayoutManager(it.context)
            it.adapter = RfidAdapter(mItemList)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    override fun finish() {
        super.finish()
        uhfKernel.scan!!.startOrStop(false)
    }

    private fun refreshList(list: List<String>?) {
        mItemList.clear()
        //编辑数据
        if (!onAccessRefreshList(list, mItemList)) {
            return
        }
        //刷新
        rv?.adapter?.notifyDataSetChanged()
        setHintTv(mItemList.size, rate, time)
        if (mItemList.isEmpty()) {
            save_ll!!.isEnabled = false
            return
        }
        save_ll!!.isEnabled = true
        //移动到最后一个item
        (rv!!.layoutManager as LinearLayoutManager?)!!.scrollToPositionWithOffset(
            mItemList.size - 1,
            0
        )
    }

    protected open fun setHintTv(count: Int, rate: Int, time: Long) {
        hint_tv!!.text = String.format(
            "已读：%d个，总数：%d条，速度：%d个/秒，耗时：%d秒",
            count,
            count,
            rate,
            time
        )
        this.rate = rate
        this.time = time
    }

    override fun initEvent() {
        super.initEvent()

        //开始
        start_iv!!.setOnClickListener {
            if (uhfKernel.scan.isScanning()) {
                //除了停止事件。如果正在入库中，不能点击事件
                uhfKernel.scan.startOrStop(false)
            } else {
                uhfKernel.scan.startOrStop(true)
            }
        }

        //清除
        clear_tv!!.setOnClickListener(View.OnClickListener {
            if (uhfKernel.scan.isScanning()) {
                //除了停止事件。如果正在入库中，不能点击事件
                return@OnClickListener
            }

            dfHint("是否清空读码数据?") {
                if (it) {
                    normalList.clear()
                    uhfKernel.scan!!.clear()
                    setHintTv(0, 0, 0)
                }
            }.show(supportFragmentManager, "")

        })

        //保存
        save_ll?.click {
            if (uhfKernel.scan.isScanning()) {
                uhfKernel.scan.startOrStop(false)
            }
            if (mItemList.isEmpty()) {
                ToastUtils.showToast("还未扫到托盘数据！")
            } else {
                dispatchNextStep(mItemList)
            }
        }
    }


    /**
     * create by lwj at 2023/4/26
     * 访问刷新的数据
     * @return true:表示继续执行 false：停止执行
     */
    abstract fun onAccessRefreshList(
        sourceList: List<String>?,
        targetList: ArrayList<String>,
    ): Boolean

    //下一步
    abstract fun dispatchNextStep(mList: ArrayList<String>)
}